<template>
  <a-modal
    v-model:open="visible"
    :mask-closable="false"
    width="70%"
    title="关联零售品"
    :dialog-style="{ top: '20px' }"
  >
    <div style="background: #ececec" v-loading="loading">
      <a-form ref="formRef" :model="formData">
        <vxe-grid
          resizable
          show-overflow
          highlight-hover-row
          keep-source
          row-id="id"
          :columns="column"
          :toolbar-config="toolbarConfig"
          :data="formData"
          :height="450"
          :scroll-y="{
            enabled: true,
            gt: 0,
          }"
        >
          <!-- 工具栏 -->
          <template #toolbar_buttons>
            <a-space>
              <a-button type="primary" @click="add()"> 添加 </a-button>
            </a-space>
          </template>
          <!-- 商品 -->
          <template #name_default="{ rowIndex, row }">
            <a-form-item :name="[rowIndex, 'productId']" no-style required>
              <product-selector
                v-model:value="row.productId"
                :request-params="{
                  productType: [1, 4].join(','),
                  categoryTypes: [2, 3, 4].join(','),
                }"
                @input-row="
                  (rowData) => {
                    if (!!rowData) {
                      if (
                        !formData.find(
                          (item) =>
                            item.code === rowData?.code && item.skuCode === rowData?.skuCode,
                        )
                      ) {
                        row.code = rowData?.code;
                        row.name = rowData?.name;
                        row.skuCode = rowData?.skuCode;
                        row.unit = rowData?.unit;
                        row.spec = rowData?.spec;
                        row.categoryName = rowData?.categoryName;
                        row.brandName = rowData?.brandName;
                        row.retailPrice = rowData?.retailPrice;
                        row.available = rowData.available;
                      } else {
                        _This().$msg.createWarning('已添加');
                        row.productId = null;
                        row.code = null;
                        row.name = null;
                        row.skuCode = null;
                        row.unit = null;
                        row.spec = null;
                        row.categoryName = null;
                        row.brandName = null;
                        row.retailPrice = null;
                        row.available = null;
                      }
                    }
                  }
                "
                @load-complete="
                  (rowDatas) => {
                    $nextTick(() => {
                      const rowData = rowDatas[0];
                      row.code = rowData?.code;
                      row.name = rowData?.name;
                      row.skuCode = rowData?.skuCode;
                      row.unit = rowData?.unit;
                      row.spec = rowData?.spec;
                      row.categoryName = rowData?.categoryName;
                      row.brandName = rowData?.brandName;
                      row.retailPrice = rowData?.retailPrice;
                      row.available = rowData.available;
                    });
                  }
                "
              />
            </a-form-item>
          </template>
          <!-- 单位 -->
          <template #unit_default="{ row }">
            <unit-selector :value="row.unit" read-only />
          </template>
          <!-- 状态 -->
          <template #available_default="{ row }">
            <available-tag :available="row.available" />
          </template>
          <!-- 操作 -->
          <template #action_default="{ rowIndex }">
            <a-space>
              <a-button type="link" @click="() => formData.splice(rowIndex, 1)" danger>
                删除
              </a-button>
            </a-space>
          </template>
        </vxe-grid>
      </a-form>
    </div>
    <template #footer>
      <div class="form-modal-footer">
        <a-space>
          <a-button type="primary" :loading="loading" html-type="submit" @click="submit">
            确认
          </a-button>
          <a-button :loading="loading" @click="closeDialog">取消</a-button>
        </a-space>
      </div>
    </template>
  </a-modal>
</template>

<script setup>
  import { getCurrentInstance, ref } from 'vue';
  import * as api from '@/api/base-data/make';
  import ProductSelector from '@/components/Selector/src/ProductSelector.vue';
  import UnitSelector from '@/components/Selector/src/UnitSelector.vue';
  import AvailableTag from '@/components/Tag/src/AvailableTag.vue';

  // this对象
  const instance = getCurrentInstance();

  const emit = defineEmits(['confirm', 'close']);

  const visible = ref(false);

  // 加载中
  const loading = ref(false);

  const props = defineProps({
    makeId: {
      type: String,
      required: true,
    },
  });

  const formRef = ref();

  const formData = ref([]);

  const column = ref([
    { field: 'code', title: '商品编号', width: 120 },
    { field: 'name', title: '商品名称', minWidth: 140, slots: { default: 'name_default' } },
    { field: 'skuCode', title: '商品SKU编号', width: 120 },
    { field: 'unit', title: '单位', width: 80, slots: { default: 'unit_default' } },
    { field: 'spec', title: '规格', width: 140 },
    { field: 'categoryName', title: '商品分类', width: 120 },
    { field: 'brandName', title: '商品品牌', width: 120 },
    { field: 'retailPrice', title: '零售价（元）', width: 100 },
    { field: 'available', title: '状态', width: 80, slots: { default: 'available_default' } },
    { title: '操作', width: 80, fixed: 'right', slots: { default: 'action_default' } },
  ]);

  const toolbarConfig = ref({
    zoom: false,
    refresh: false,
    custom: false,
    // 自定义左侧工具栏
    slots: {
      buttons: 'toolbar_buttons',
    },
  });

  // 添加
  const add = () => {
    formData.value.push({});
  };

  const initFormData = () => {
    formData.value = [];
  };

  const loadFormData = () => {
    loading.value = true;
    api
      .getProductMake(props.makeId)
      .then((res) => {
        res.forEach((item) => {
          formData.value.push({
            productId: item.productId,
            code: item.code,
            skuCode: item.skuCode,
          });
        });
      })
      .finally(() => {
        loading.value = false;
      });
  };

  const submit = () => {
    formRef.value.validate().then(() => {
      // _This().$msg.createSuccess('验证成功！');

      const params = formData.value.map((item) => {
        return {
          makeId: props.makeId,
          code: item.code,
          skuCode: item.skuCode,
          name: item.name,
        };
      });
      loading.value = true;
      api
        .createProductMake(props.makeId, params)
        .then(() => {
          _This().$msg.createSuccess('保存成功！');
          emit('confirm');
          visible.value = false;
        })
        .finally(() => {
          loading.value = false;
        });
    });
  };

  // 打开弹窗
  const openDialog = () => {
    visible.value = true;
    initFormData();

    loadFormData();
  };

  // 关闭对话框
  const closeDialog = () => {
    visible.value = false;
    emit('close');
  };

  // 组件实例对象
  const _This = () => {
    return instance.appContext.config.globalProperties;
  };

  defineExpose({
    openDialog,
  });
</script>

<style scoped></style>
